const audioEle = document.querySelector('audio')

const cvs = document.getElementById('canvas')
const cvs1 = document.getElementById('canvas1')
const ctx = cvs.getContext('2d')
const ctx1 = cvs1.getContext('2d')

function initCvs() {
  cvs.width = window.innerWidth * devicePixelRatio
  cvs1.width = window.innerWidth * devicePixelRatio
  cvs.height = window.innerHeight * devicePixelRatio * 2 / 5
  cvs1.height = window.innerHeight * devicePixelRatio * 2 / 5
}
initCvs()

let isInit = false;
let dataArray, analyser;
audioEle.onplay = function () {
  if (isInit) {
    return
  }
  const audioCtx = new AudioContext(); // 创建音频上下文
  const source = audioCtx.createMediaElementSource(audioEle); // 创建音频源节点
  analyser = audioCtx.createAnalyser();
  analyser.fftSize = 512;
  dataArray = new Uint8Array(analyser.frequencyBinCount);
  source.connect(analyser);
  analyser.connect(audioCtx.destination)

  isInit = true
}

function draw() {
  requestAnimationFrame(draw)
  if (!isInit) return;
  const { width, height } = cvs
  ctx.clearRect(0, 0, width, height)
  ctx1.clearRect(0, 0, width, height)

  analyser.getByteFrequencyData(dataArray)
  const len = dataArray.length;
  const barWidth = width / len
  const unitHeight = height / 255
  ctx.fillStyle = document.getElementById('color').value
  ctx1.fillStyle = document.getElementById('color').value
  
  for (let i = 0; i < len; i++) {
    const data = dataArray[i];
    const barHeight = data * unitHeight
    const x = i * barWidth
    const x1 = x + width / 2;
    const x2 = width / 2 - x
    const y = height - barHeight;
    if (i < len / 2) {
      ctx.fillRect(x1, y, barWidth - 2, barHeight)
      ctx.fillRect(x2, y, barWidth - 2, barHeight)
    }
    ctx1.fillRect(x, y, barWidth - 2, barHeight)
  }

}
draw()


